package com.apes.fn.scm.retailOrder.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.insuranceRules.InsuranceRule;
import com.apes.fn.scm.insuranceRules.InsuranceRuleService;
import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.model.RetailOrderItem;
import com.apes.fn.scm.retailOrder.repository.RetailOrderRepository;
import com.apes.fn.scm.retailOrder.service.account.RetailAccountData;
import com.apes.fn.scm.retailOrder.service.account.RetailAccountService;
import com.apes.fn.server.productReceive.ProductReceiveItem;
import com.apes.fn.server.productReceive.ProductReceiveItemRepository;
import com.apes.fn.server.productReturn.ProductReturn;
import com.apes.fn.server.productReturn.ProductReturnItem;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.fn.server.workOrder.model.MaintenanceOrder;
import com.apes.fn.server.workOrder.repository.MaintenanceOrderRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.model.AccountingMethod;
import com.apes.scm.account.account.model.InventoryBatch;
import com.apes.scm.account.account.model.InventoryMode;
import com.apes.scm.account.account.service.InventoryService;
import com.apes.scm.account.account.service.ProductAccountService;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.contract.service.ContractService;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.sal.saleOrder.SaleOrder;
import com.apes.scm.sal.saleOrder.SaleOrderItem;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherInventory;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.repository.VoucherInventoryRepository;
import com.apes.scm.voucher.service.BusinessType;
import com.apes.scm.voucher.service.VoucherType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
 * 分销订单流程
 *
 * @author wuq
 * @create 2020-06-18 20:30
 */
@Service
public class SaleOrderFlowService extends DomainService {

    @Autowired
    private TaxService taxService;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private PartyRoleRepository partyRoleRepository;
    @Autowired
    private ProductAccountService productAccountService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private VoucherInventoryRepository voucherInventoryRepository;
    @Autowired
    private ProductReceiveItemRepository productReceiveItemRepository;
    @Autowired
    private ServicePlanItemRepository servicePlanItemRepository;
    @Autowired
    private OrderPaintProductService orderPaintProductService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private RetailAccountService retailAccountService;


    /**
     * 自动归还
     *
     * @param request List<ServicePlanItem>
     */
    public void autoReturn(SimpleRequest request) {
        JSONArray array = request.getJA();
        List<ProductReturn> productReturns = invoke("saleOrderFlow.create.productReturn", array);
        invoke("stock.productReturnList.create", MapUtil.mapped(productReturns));
    }

    private boolean isNeedProductReturn(ServicePlanItem servicePlanItem) {
        return servicePlanItem.getProduct().getProductGroup().checkPartProduct()
                && !"outer".equals(servicePlanItem.getAssistType().getCode())   // 配件外协部分
                && Objects.isNull(servicePlanItem.getInventoryBatch());
    }

    /**
     * 构造商品归还单
     *
     * @param request List<ServicePlanItem>
     * @return List<ProductReturn>
     */
    public List<ProductReturn> createProductReturn(SimpleRequest request) {
        JSONArray array = request.getJA();
        List<ServicePlanItem> servicePlanItemList = array.stream().map(tempJson -> MapUtil.getO(tempJson, ServicePlanItem.class)).collect(Collectors.toList());

        List<ProductReturn> productReturns = new ArrayList<>();
        servicePlanItemList.stream().filter(this::isNeedProductReturn)
                .collect(groupingBy(ServicePlanItem::getLocation))
                .forEach((location, servicePlanItems) -> {

                    List<ProductReturnItem> returnItem = new ArrayList<>();

                    ProductReturn productReturn = new ProductReturn();
                    productReturn.setLocation(location);
                    productReturn.setCompany(location.getCompany());     // 公司为库区的公司

                    servicePlanItems.forEach(servicePlanItem -> {
                        // 查询
                        List<ProductReceiveItem> productReceiveItems = productReceiveItemRepository.findAllByServicePlanItemId(servicePlanItem.getId());
                        double sumNotReturn = productReceiveItems.stream().mapToDouble(ProductReceiveItem::getQtyNotReturn).sum();
                        double saleQty = servicePlanItem.getSaleQty() - servicePlanItem.getQtyEnd();
                        if (sumNotReturn != saleQty) {
                            throw new RuntimeException("服务单中销售数量与领用单可归还数量不相等，方案明细编码为：" + servicePlanItem.getId() +
                                    "，商品编码为：" + servicePlanItem.getProduct().getId());
                        }

                        productReceiveItems.forEach(productReceiveItem -> {
                            ProductReturnItem items = new ProductReturnItem();
                            items.setProduct(productReceiveItem.getProduct());
                            items.setUom(productReceiveItem.getUom());
                            items.setQtyReturn(productReceiveItem.getQtyNotReturn());
                            items.setCompany(productReceiveItem.getCompany());
                            items.setRemark("服务单生成分销单时自动归还");
                            items.setProductReceiveItem(productReceiveItem);
                            items.setProductReturn(productReturn);
                            returnItem.add(items);
                        });
                    });

                    // 从基地的服务单中取业务员、来源单号
                    ServicePlanItem servicePlanItemTemp = servicePlanItemRepository.findOne(servicePlanItemList.get(0).getId());
                    productReturn.setSource(servicePlanItemTemp.getServicePlan().getId());
                    productReturn.setSourceBusinessType(ServicePlan.class.getSimpleName());
                    productReturn.setSourceBusinessTypeName("服务单");
                    productReturn.setProductReturnItems(returnItem);
                    productReturn.setRemark("服务单生成分销单时自动归还");
                    productReturns.add(productReturn);
                });
        return productReturns;
    }


    /**
     * 创建销售订单
     *
     * @param request 零售来源 {"deptId": xx, "companyId": xx, "customer": xx, "source": retailOrder , "items" : List<ServicePlanItem>}
     *                服务来源 {"deptId": xx, "companyId": xx, "customer": xx, "items": List<ServicePlanItem>}
     * @return List<SaleOrder>
     */
    public List createSaleOrder(SimpleRequest request) {
        JSONObject json = request.getJO();
        JSONArray array = json.getJSONArray("items");
        List<ServicePlanItem> servicePlanItemList = array.stream().map(tempJson -> MapUtil.getO(tempJson, ServicePlanItem.class)).collect(Collectors.toList());
        if (servicePlanItemList.size() == 0) return null;

        Dept dept = deptRepository.findOne(json.getString("deptId"));
        PartyRole company = partyRoleRepository.findOne(json.getString("companyId"));
        PartyRole customer = partyRoleRepository.findOne(json.getString("customerId"));
        List<SaleOrder> saleOrderModels = createSaleOrderModel(dept, company, customer, json.getString("source"), servicePlanItemList);
        return MapUtil.mapped(saleOrderModels);
    }

    /**
     * 创建分销单模型
     *
     * @param dept             部门
     * @param company          公司
     * @param customer         客户
     * @param source           来源号码（零售单号）
     * @param servicePlanItems 服务方案明细数组
     * @return List<SaleOrder>
     */
    private List<SaleOrder> createSaleOrderModel(Dept dept, PartyRole company, PartyRole customer, String source, List<ServicePlanItem> servicePlanItems) {
        // 查询销售合同
        Contract contract = contractService.getContract(dept, customer, "distribution", "customer", "内协销售业务");

        List<SaleOrder> saleOrders = new ArrayList<>();
        servicePlanItems.stream()
                .collect(Collectors.groupingBy(ServicePlanItem::getLocation))
                .forEach((location, servicePlanItemList) -> {
                    SaleOrder saleOrder = new SaleOrder();
                    saleOrder.setDept(dept);
                    saleOrder.setCompany(company);
                    saleOrder.setCustomer(customer);
                    saleOrder.setState("confirmed");
                    saleOrder.setRemark("由内协跨公司产生分销单");

                    Set<SaleOrderItem> saleOrderItems = new HashSet<>();
                    servicePlanItemList.forEach(servicePlanItem -> {
                        SaleOrderItem saleOrderItem = new SaleOrderItem();

                        saleOrderItem.setSaleOrder(saleOrder);
                        saleOrderItem.setProduct(servicePlanItem.getProduct());

                        saleOrderItem.setTax(saleOrderItem.computeTax());
                        saleOrderItem.setUom(servicePlanItem.getUom());           // 计量单位
                        saleOrderItem.setPriceUnit(servicePlanItem.getPftPriceUnit()); // 单价
                        saleOrderItem.setProductUomQty(servicePlanItem.getSaleQty() - servicePlanItem.getQtyEnd());  // 数量
                        saleOrderItem.setPriceTotal(servicePlanItem.getSalesAmount());     // 金额
                        saleOrderItem.setOriginItemId(servicePlanItem.getId());            // 保存服务明细号
                        saleOrderItem.setProductRule(servicePlanItem.calcProductRule());   // 商品规则

                        // 由于存在询价时会记录一个供应商字段，避免在生成销售凭证时报错，这里增加控制，存在批次时才去记录供应商（外协+内协场景一定会存在批次与供应商）
                        if (servicePlanItem.getInventoryBatch() != null) {
                            saleOrderItem.setInventoryBatch(servicePlanItem.getInventoryBatch());
                            saleOrderItem.setSupplier(servicePlanItem.getSupplier());
                        }

                        // 对应代销带安单独处理
                        if (saleOrderItem.getProductRule() == 10) {
                            List<String> types = Collections.singletonList("out");
                            MaintenanceOrder maintenanceOrder = SpringManager.getBean(MaintenanceOrderRepository.class).findFirstByServicePlanItemAndBusinessTypeNotIn(servicePlanItem, types);
                            if (maintenanceOrder != null) {
                                saleOrderItem.setSupplier(maintenanceOrder.getSupplier());
                                saleOrderItem.setInnerSalePriceUnit(maintenanceOrder.getPriceCostUnitInTax());   // 门店找车宝或者供应商采购价
                                saleOrderItem.setPriceOutUnitInTax(maintenanceOrder.getPlatformPriceCosInTax()); // 门店找车宝，车宝找供应商采购价
                                saleOrderItem.setContract(maintenanceOrder.getContract());
                            }
                        }
                        saleOrderItems.add(saleOrderItem);
                    });
                    if (saleOrderItems.size() == 0) return;

                    saleOrder.setSaleItems(saleOrderItems);
                    saleOrder.setLocation(location);

                    saleOrder.setContract(contract);
                    saleOrder.setMoveType(contract.getMoveType());
                    saleOrder.setCooperation(contract.getCooperation());

                    // 从基地的服务单中取业务员、来源单号
                    ServicePlanItem servicePlanItemTemp = servicePlanItemRepository.findOne(servicePlanItemList.get(0).getId());
                    saleOrder.setOrigin(servicePlanItemTemp.getServicePlan().getId());
                    saleOrder.setOriginBusinessType(ServicePlan.class.getSimpleName());
                    saleOrder.setClerk(servicePlanItemTemp.getServicePlan().getConfirmUid());
                    saleOrder.setSource(source);
                    saleOrder.setSourceBusinessType(RetailOrder.class.getSimpleName());
                    saleOrder.setOrderType("RETAIL_SALE");  // 设置单据类型

                    // 由内协调用的没有传 source，需要调整来源单号
                    if (StringUtils.isEmpty(source)) {
                        saleOrder.setSource(servicePlanItemTemp.getServicePlan().getId());
                        saleOrder.setSourceBusinessType(ServicePlan.class.getSimpleName());
                        saleOrder.setOrigin(servicePlanItemTemp.getParentServicePlanItem().getServicePlan().getId());
                        saleOrder.setOriginBusinessType(ServicePlan.class.getSimpleName());
                        saleOrder.setOrderType("INNER_SALE");  // 设置单据类型，内协销售
                    }
                    saleOrder.setFnCustomerExpandId(servicePlanItemTemp.getServicePlan().getFnCustomerExpand().getId());    // 增加车主客户信息
                    double amt = saleOrderItems.stream().mapToDouble(SaleOrderItem::getPriceTotal).sum();
                    saleOrder.setAmtTotal(amt);

                    saleOrders.add(saleOrder);
                });

        return saleOrders;
    }

    /**
     * 循环调用、商品出库
     *
     * @param request SaleOrder
     * @return SaleOrder
     */
    public SaleOrder productOutput(SimpleRequest request) {
        SaleOrder saleOrder = request.getO(SaleOrder.class);

        // 配件类商品写保管数
        partProductOutPut(saleOrder);

        // 服务类商品、油漆商品写内部采购凭证
        workProductOutPut(saleOrder);

        // 带安商品、代销带安商品
        retailAccountService.process("saleOut", new RetailAccountData(saleOrder));
        return saleOrder;
    }

    private void partProductOutPut(SaleOrder saleOrder) {
        Set<Map> items = new HashSet<>();
        saleOrder.getSaleItems().stream()
                .filter(saleOrderItem -> saleOrderItem.getProductRule() == 0)
                .forEach(saleOrderItem -> {
                    // 减保管数
                    productAccountService.setProductCustody(saleOrderItem.getProduct(), saleOrder.getLocation(), saleOrderItem.getUom(),
                            -1 * Math.abs(saleOrderItem.getProductUomQty()), saleOrder.getInnerBusinessType(), saleOrder.getId(),
                            saleOrderItem.getId(), "分销单自动发货", saleOrder.getCompany());

                    Map<String, Object> map = new HashMap<>();
                    map.put("originItemId", saleOrderItem.getId());
                    map.put("qtyDone", saleOrderItem.getProductUomQty());
                    items.add(map);
                });

        Map<String, Object> result = new HashMap();
        result.put("originBusinessType", SaleOrder.class.getSimpleName());
        result.put("origin", saleOrder.getId());
        result.put("items", items);

        sendSynEvent("event:stock.pick.delivery", result);  // 发送收货事件
    }

    private void workProductOutPut(SaleOrder saleOrder) {
        List<SaleOrderItem> saleOrderItems = saleOrder.getSaleItems().stream()
                .filter(saleOrderItem -> saleOrderItem.getProductRule() == 30)
                .collect(Collectors.toList());
        if (saleOrderItems.size() == 0) return;

        saleOrderItems.stream()
                .map(item -> orderPaintProductService.setPaintInfo(saleOrder.getDept().getId(), item))
                .collect(Collectors.groupingBy(SaleOrderItem::isPaintFlag))
                .forEach((flag, items) -> {
                    if (flag) {
                        //  油漆商品
                        retailAccountService.process("salePaint", new RetailAccountData(saleOrder, items));
                    } else {
                        serviceProductVoucher(saleOrder, items);   //  服务商品
                    }
                });
    }

    private void serviceProductVoucher(SaleOrder saleOrder, List<SaleOrderItem> saleOrderItems) {
        Voucher voucher = getDefaultVoucher(saleOrder, BusinessType.PURCHASE_ORDER);
        voucher.setPartner(saleOrder.getCompany().getParty().getPatyRoleByType("Supplier"));

        voucher.setInventoryMode(InventoryMode.IM_OWN);     //设置库存模式：自有经销
        voucher.setAccountingMethod(AccountingMethod.AM_PURCHASE);  // 核算方式：采购
        voucher.setClassification(VoucherType.SERVICE_PRODUCT);
        voucher.setCustomerExpand(saleOrder.getFnCustomerExpandId());

        PartyRole supplier = voucher.getPartner();
        voucher.setVoucherItems(
                saleOrderItems.stream().map(item -> {
                    VoucherItem voucherItem = new VoucherItem();

                    voucherItem.setProduct(item.getProduct());
                    voucherItem.setOwner(saleOrder.getCompany());
                    voucherItem.setUom(item.getUom());
                    voucherItem.setProductQty(item.getProductUomQty());

                    voucherItem.setOriginItemId(item.getId());
                    voucherItem.setSourceItemId(item.getId());
                    voucherItem.setSupplier(item.getSupplier());

                    Tax tax = taxService.getPurchaseTax(saleOrder.getCompany(), supplier, item.getProduct());//供应商进项税
                    voucherItem.setTax(tax);

                    voucherItem.setPriceUnit(0);
                    return voucherItem;
                }).collect(Collectors.toSet())
        );

        voucher = invoke("voucher.create", MapUtil.mapped(voucher));

        // 回写明细批次
        backBathAndSupplier(voucher);
    }

    private Voucher getDefaultVoucher(SaleOrder saleOrder, String businessType) {
        Voucher voucher = new Voucher();

        voucher.setDept(saleOrder.getDept());
        voucher.setCompany(saleOrder.getCompany());
        voucher.setBusinessType(businessType);

        voucher.setClerk(saleOrder.getClerk()); //业务员
        voucher.setScene(saleOrder.getScene());
        voucher.setOrigin(saleOrder.getOrigin());
        voucher.setOriginBusinessType(ServicePlan.class.getSimpleName());
        voucher.setSource(saleOrder.getId());
        voucher.setSourceBusinessType(saleOrder.getInnerBusinessType());
        return voucher;
    }

    private void backBathAndSupplier(Voucher voucher) {
        List lists = voucher.getVoucherItems().stream()
                .map(voucherItem -> {
                    VoucherInventory voucherInventory = voucherInventoryRepository.findByVoucherItem(voucherItem).stream().findAny().orElseThrow(() -> new RuntimeException("找不到批次信息！"));
                    InventoryBatch inventoryBatch = voucherInventory.getInventoryBatch();

                    inventoryService.changeFrostQty(inventoryBatch, inventoryBatch.getUom(), inventoryBatch.getPurchaseQty(), voucher.getCompany(), voucher.getInnerBusinessType(), voucher.getId(), String.valueOf(voucherItem.getId()), "带安/服务/油漆商品生成分销冻结批次");
                    // 单独处理油漆供应
                    String supplierId = voucher.getPartner().getId();
                    if (VoucherType.PAINT_PRODUCT.equals(voucher.getClassification())) {
                        supplierId = voucherItem.getSupplier().getId();
                    }

                    return MapUtil.mapper("id", voucherItem.getOriginItemId(), "supplierId", supplierId, "batchId", inventoryBatch.getId(),
                            "classification", voucher.getClassification(), "priceUint", voucherItem.getPriceUnit());
                }).collect(Collectors.toList());
        sendSynEvent("event:saleOrder.setBatchAndSupplier", MapUtil.mapper("id", voucher.getSource(), "items", lists));
    }

    /**
     * 创建销售凭证以及账单
     *
     * @param request
     * @return
     */
    public Voucher createSaleVoucher(SimpleRequest request) {
        SaleOrder saleOrder = request.getO(SaleOrder.class);
        Voucher voucher = getDefaultVoucher(saleOrder, BusinessType.SALE_ORDER);
        voucher.setPartner(saleOrder.getCustomer().getParty().getPatyRoleByType("Customer"));

        Contract contract = contractService.getContract(voucher.getDept(), voucher.getPartner(), "distribution", "customer", "内协分销单销售业务");
        voucher.setContract(contract);
        voucher.setInventoryMode(voucher.getContract().getCooperation().getInventoryMode());     //设置库存模式
        voucher.setAccountingMethod(voucher.getContract().getCooperation().getAccountingMethod());  // 核算方式
        voucher.setCustomerExpand(saleOrder.getFnCustomerExpandId());
        if ("INNER_SALE".equals(saleOrder.getOrderType())) {
            // 内协销售
            voucher.setClassification(VoucherType.WHOLE_INNER_HELP);
        } else {
            // 定损销售
            voucher.setClassification(VoucherType.INSURANCE);
        }

        voucher.setVoucherItems(
                saleOrder.getSaleItems().stream().map(
                        item -> {
                            VoucherItem voucherItem = new VoucherItem();

                            voucherItem.setProduct(item.getProduct());
                            voucherItem.setOwner(saleOrder.getCompany());
                            voucherItem.setUom(item.getUom());
                            voucherItem.setTax(item.getTax());

                            voucherItem.setProductQty(item.getProductUomQty());
                            voucherItem.setPriceUnit(item.getPriceUnit());
                            voucherItem.setPriceTotal(item.getPriceTotal());

                            voucherItem.setOriginItemId(item.getOriginItemId());
                            voucherItem.setSourceItemId(item.getId());
                            voucherItem.setSupplier(item.getSupplier());
                            voucherItem.setInventoryBatch(item.getInventoryBatch());

                            return voucherItem;
                        }).collect(Collectors.toSet())
        );
        voucher = invoke("voucher.create", MapUtil.mapped(voucher));

        // 生成账单时，修改源单据以及源单据类型
        Map m = invoke("voucher.flow.invoice", MapUtil.mapped(voucher));
        if ("INNER_SALE".equals(saleOrder.getOrderType())) {
            // 内协来源：基地服务方案号
            m.put("origin", saleOrder.getSource());
            m.put("originBusinessType", saleOrder.getSourceBusinessType());
        } else {
            // 定损来源：定损报价单号
            RetailOrder retailOrder = SpringManager.getBean(RetailOrderRepository.class).findOne(saleOrder.getSource());
            m.put("origin", retailOrder.getSource());
            m.put("originBusinessType", retailOrder.getSourceBusinessType());
        }
        invoke("invoice.create", m);

        return voucher;
    }

    /**
     * 根据零售单创建对保险公司分销单
     *
     * @param request retailOrder
     * @return List<SaleOrder>
     */
    public List<SaleOrder> createInsuranceSaleOrderByRetailOrder(SimpleRequest request) {
        RetailOrder retailOrder = request.getO(RetailOrder.class);

        InsuranceRule insuranceRule = SpringManager.getBean(InsuranceRuleService.class)
                .findByDeptAndInsuranceCompany(retailOrder.getServiceDept(), retailOrder.getInsuranceCompany());

        // 查询销售合同  基地 --> 保险销售公司
        Contract contract = contractService.getContract(retailOrder.getServiceDept(), insuranceRule.getCompany(), "distribution", "customer", "分销单油漆采购业务");

        List<SaleOrder> saleOrders = new ArrayList<>();
        retailOrder.getSaleItems().stream()
                .collect(Collectors.groupingBy(RetailOrderItem::getLocation))
                .forEach((location, orderItemList) -> {

                    Set<SaleOrderItem> saleOrderItems = new HashSet<>();
                    orderItemList.forEach(item -> {
                        SaleOrderItem saleOrderItem = new SaleOrderItem();
                        saleOrderItem.setProduct(item.getProduct());

                        saleOrderItem.setTax(saleOrderItem.computeTax());
                        saleOrderItem.setUom(item.getUom());             // 计量单位
                        saleOrderItem.setPriceUnit(item.getPriceUnit()); // 单价
                        saleOrderItem.setProductUomQty(item.getProductUomQty());  // 数量
                        saleOrderItem.setPriceTotal(item.getPriceTotal());     // 金额
                        saleOrderItem.setOriginItemId(item.getId());           // 保存明细号
                        saleOrderItem.setProductRule(item.getProductRule());
                        saleOrderItem.setSupplier(item.getSupplier());
                        saleOrderItems.add(saleOrderItem);
                    });
                    if (saleOrderItems.size() == 0) return;

                    SaleOrder saleOrder = new SaleOrder();
                    saleOrder.setSaleItems(saleOrderItems);
                    saleOrder.setLocation(location);
                    saleOrder.setAmtTotal(saleOrder.getAmtTotal());

                    saleOrder.setDept(retailOrder.getServiceDept());
                    saleOrder.setCompany(retailOrder.getServiceDept().getCompany());
                    saleOrder.setCustomer(insuranceRule.getCompany());
                    saleOrder.setState("confirmed");
                    saleOrder.setRemark("零售生成基地对保险销售公司的分销单");

                    saleOrder.setContract(contract);
                    saleOrder.setMoveType(contract.getMoveType());
                    saleOrder.setCooperation(contract.getCooperation());

                    // 从基地的服务单中取业务员、来源单号
                    saleOrder.setSource(retailOrder.getId());
                    saleOrder.setSourceBusinessType(RetailOrder.class.getSimpleName());
                    saleOrder.setClerk(retailOrder.getClerk());
                    saleOrder.setFnCustomerExpandId(retailOrder.getCustomerExpand().getId());

                    saleOrders.add(saleOrder);
                });

        return saleOrders;
    }

}
